﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using Microsoft.SharePoint;
using PIT.Labs.SharePoint.Extensions;
using System.Web.UI;
using PIT.Labs.SharePoint.Logger;
using PIT.Labs.SharePoint.Extensions.Helper;

namespace PIT.Labs.ProjectRepository.WebParts.ListRandomizerWebPart.ListRandomizerWebPart
{
    /// <summary>
    /// Provides a tool pane for web parts that contains all names of lists of a web site.
    /// WARNING: Uses elevated rights!
    /// </summary>
    public class ListEditorPart : EditorPart
    {

        private Label lblLists = null;
        private DropDownList ddlLists = null;
        private CustomValidator cvList = null;

        /// <summary>
        /// Creates a set of child controls that are contained in this pane.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.Title = SPUtility.GetLocalizedString("$Resources:CONNECTION", ListRandomizerWebPart.RESOURCES_FILE, (uint)CultureInfo.CurrentUICulture.LCID);

            this.lblLists = new Label();
            this.lblLists.Text = SPUtility.GetLocalizedString("$Resources:LIST", ListRandomizerWebPart.RESOURCES_FILE, (uint)CultureInfo.CurrentUICulture.LCID);
            this.lblLists.CssClass = "UserSectionHead";

            this.ddlLists = new DropDownList();
            AddListNamesToDropDownList();
            this.cvList = new CustomValidator();
            this.cvList.ControlToValidate = this.ddlLists.ID;
            this.cvList.EnableClientScript = true;
            this.cvList.ErrorMessage = SPUtilityHelper.GetLocalizedString("ERR002", ListRandomizerWebPart.RESOURCES_FILE);

            this.Controls.Add(new LiteralControl(@"<div class=""UserSectionHead"">"));
            this.Controls.Add(this.lblLists);
            this.Controls.Add(new LiteralControl(@"</div>"));
            this.Controls.Add(new LiteralControl(@"<div class=""UserSectionBody"">"));
            this.Controls.Add(new LiteralControl(@"<div class=""UserControlGroup"">"));
            this.Controls.Add(this.ddlLists);
            this.Controls.Add(new LiteralControl(@"<br />"));
            this.Controls.Add(this.cvList);
            this.Controls.Add(new LiteralControl(@"</div>"));
            this.Controls.Add(new LiteralControl(@"</div>"));
        }

        private void AddListNamesToDropDownList()
        {
            SortedList<String, Guid> listNames = new SortedList<String, Guid>();
            using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPSite elevatedSite = siteCollection.GetElevatedSite())
                {
                    using (SPWeb elevatedWeb = elevatedSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        foreach (SPList list in elevatedWeb.Lists)
                        {
                            if (list.Hidden == false)
                                listNames.Add(list.Title, list.ID);
                        }
                    }
                }
            }
            foreach (String listName in listNames.Keys)
                this.ddlLists.Items.Add(new ListItem(listName, listNames[listName].ToString("D", CultureInfo.InvariantCulture)));
        }

        /// <summary>
        /// This method is executed when the user clicks OK or Apply and sets the value of the list property of the <see cref="T:PIT.Labs.ProjectRepository.WebParts.ListRandomizerWebPart.ListRandomizerWebPart.ListRandomizerWebPart"/>.
        /// </summary>
        /// <returns>
        /// <see cref="Boolean"/><br />
        /// <b>true</b>, if the selected value is valid, else <b>false</b>.
        /// </returns>
        public override bool ApplyChanges()
        {
            try
            {
                EnsureChildControls();
                String listIDString = this.ddlLists.SelectedValue;
                if (!String.IsNullOrEmpty(listIDString))
                {
                    Guid listID = new Guid(this.ddlLists.SelectedValue);
                    if (SPContext.Current.Web.ContainsList(listID))
                    {
                        this.cvList.IsValid = true;
                        ((ListRandomizerWebPart)this.WebPartToEdit).ListID = listID;
                    }
                    else
                    {
                        this.cvList.IsValid = false;
                        return false;
                    }
                }
                else
                {
                    this.cvList.IsValid = false;
                    return false;
                }
            }
            catch (Exception ex)
            {
                SPLogger logger = new SPLogger();
                logger.Log(NLog.LogLevel.Error, SPUtilityHelper.GetLocalizedString("ERR001", ListRandomizerWebPart.RESOURCES_FILE), ex);
                return false;
            }
            return true;
        }

        /// <summary>
        /// This method is used by the <see cref="T:PIT.Labs.ProjectRepository.WebParts.ListRandomizerWebPart.ListRandomizerWebPart.ListRandomizerWebPart"/> to get the value from the Web Part into this editor part.
        /// </summary>
        public override void SyncChanges()
        {
            EnsureChildControls();
            Guid listID = ((ListRandomizerWebPart)this.WebPartToEdit).ListID;
            if (SPContext.Current.Web.ContainsList(listID))
            {
                this.ddlLists.SelectedValue = listID.ToString("D", CultureInfo.InvariantCulture);
                this.cvList.IsValid = true;
            }
            else
            {
                ListItem emptyItem = new ListItem();
                emptyItem.Selected = true;
                this.ddlLists.Items.Add(emptyItem);
                this.cvList.IsValid = false;
            }
        }
    }
}
